package com.travel.server.manager.impl.controller;

import com.travel.common.CommonConstant;
import com.travel.common.base.BaseResponse;
import com.travel.common.excel.ExcelData;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.common.util.ExcelUtil;
import com.travel.common.util.FileUploadUtil;
import com.travel.server.manager.dto.request.customer.QueryCustomerInfoListRequest;
import com.travel.server.manager.dto.request.order.QueryOrderListRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.dto.response.file.UploadFileResponse;
import com.travel.server.manager.impl.base.BaseCommand;
import com.travel.server.manager.impl.command.customer.QueryCustomerInfoListCommand;
import com.travel.server.manager.impl.command.order.QueryOrderListCommand;
import com.travel.server.manager.impl.command.project.data.ImportProjectCostCommand;
import com.travel.server.manager.impl.command.upload.UploadFileCommand;
import com.travel.server.manager.impl.enums.UploadTypeEnum;
import com.travel.server.manager.impl.sal.CustomerSal;
import com.travel.server.manager.impl.sal.OrderSal;
import com.travel.server.manager.model.CustomerInfo;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018\11\11 0011 13:57
 * @Desc:
 */
@RestController
@Slf4j
public class UploadFileController extends BaseCommand {

    @Value("${excel.file.path}")
    private String EXCEL_FILE_PATH;

    @Value("${image.file.path}")
    private String IMAGE_FILE_PATH;

    @Value("${image.file.show.prefix}")
    private String IMAGE_FILE_SHOW_PREFIX;

    @Value("${order.template.file.path}")
    private String ORDER_TEMPLATE_FILE_PATH;

    @Value("${customer.template.file.path}")
    private String CUSTOMER_TEMPLATE_FILE_PATH;

    @Value("${project.cost.file.path}")
    private String PROJECT_COST_FILE_PATH;

    @Autowired
    private QueryOrderListCommand queryOrderListCommand;

    @Autowired
    private QueryCustomerInfoListCommand queryCustomerInfoListCommand;

    @Autowired
    private UploadFileCommand uploadFileCommand;

    @Autowired
    private ImportProjectCostCommand importProjectCostCommand;

    /**
     * 上传文件
     * @param fileData
     * @param fileSuffix 文件后缀
     * @param uploadType 文件类型，参考UploadTypeEnum
     * @return
     */
    @RequestMapping(value = "upload_file")
    public Object uploadFile(@RequestPart(value = "file_data") List<MultipartFile> fileData, @RequestParam(value = "file_suffix") String fileSuffix, @RequestParam(value = "upload_type") Integer uploadType,
                             @RequestParam(value = "is_member", required = false) Integer isMember) {
        if(CollectionUtil.isEmpty(fileData) || uploadType == null || StringUtils.isBlank(fileSuffix)){
            throw new WorkException(WorkCode.INVALID_PARAM);
        }

        UserInfo userInfo = getUserInfo();
        log.info("上传文件，文件数 {}, 文件后缀 {}, 上传类型 {}", fileData.size(), fileSuffix, uploadType);

        String dayDir = FileUploadUtil.getDayDir();
        String filePath;
        String fileName;

        MultipartFile file = fileData.get(0);
        InputStream inputStream;
        try{
            inputStream = file.getInputStream();
        }catch (Exception e){
            log.error("获取文件流异常：", e);
            throw new WorkException(WorkCode.SYSTEM);
        }

        if(uploadType.equals(UploadTypeEnum.IMPORT_ORDER.getType())){
            if(!ExcelUtil.EXCEL_SUFFIX.equals(fileSuffix)){
                throw new WorkException(WorkCode.EXCEL_FILE_NOT_CORRECT);
            }
            filePath = EXCEL_FILE_PATH + dayDir;
            uploadFileCommand.importOrder(inputStream, userInfo);
            fileName = FileUploadUtil.getExcelFileName(UploadTypeEnum.IMPORT_ORDER.getName(), userInfo.getName());
        }else if(uploadType.equals(UploadTypeEnum.IMPORT_CUSTOMER.getType())){
            if(!ExcelUtil.EXCEL_SUFFIX.equals(fileSuffix)){
                throw new WorkException(WorkCode.EXCEL_FILE_NOT_CORRECT);
            }
            filePath = EXCEL_FILE_PATH + dayDir;
            uploadFileCommand.importCustomer(inputStream, userInfo, isMember);
            fileName = FileUploadUtil.getExcelFileName(UploadTypeEnum.IMPORT_CUSTOMER.getName(), userInfo.getName());
        }else if (uploadType.equals(UploadTypeEnum.UPLOAD_PIC.getType())){
            filePath = IMAGE_FILE_PATH + dayDir;
            fileName = FileUploadUtil.getPicFileName();
        }else if(uploadType.equals(UploadTypeEnum.PROJECT_COST.getType())){
            if(!ExcelUtil.EXCEL_SUFFIX.equals(fileSuffix)){
                throw new WorkException(WorkCode.EXCEL_FILE_NOT_CORRECT);
            }
            filePath = EXCEL_FILE_PATH + dayDir;
            importProjectCostCommand.handle(inputStream, userInfo);
            fileName = FileUploadUtil.getExcelFileName(UploadTypeEnum.PROJECT_COST.getName(), userInfo.getName());
        }
        else{
            log.info("未定义类型 {}", uploadType);
            throw new WorkException(WorkCode.INVALID_PARAM);
        }
        try {
            FileUploadUtil.uploadPic(file.getInputStream(), filePath, fileName + fileSuffix);
        }catch (Exception e){
            log.error("上传文件异常：", e);
            throw new WorkException(WorkCode.SYSTEM);
        }
        UploadFileResponse response = new UploadFileResponse();
        response.setUrl(IMAGE_FILE_SHOW_PREFIX + dayDir + CommonConstant.SLASH_STR + fileName + fileSuffix);
        return BaseResponse.makeSuccess(response);
    }

    @RequestMapping(value = "download_order")
    public Object downloadOrder(@RequestBody QueryOrderListRequest request){
        request.setLimit(null);
        request.setPage(null);
        List<List<Object>> rows = queryOrderListCommand.makeExcelData(request);
        if(CollectionUtil.isEmpty(rows)){
            throw new WorkException(WorkCode.ORDER_EXCEL_DATA_NULL);
        }
        ExcelData excelData = OrderSal.makeExcelData(rows);
        ExcelUtil.exportExcel(getHttpServletResponse(), "订单报表", excelData);
        return new EmptyResponse();
    }

    @RequestMapping(value = "download_customer")
    public Object downloadCustomer(@RequestBody QueryCustomerInfoListRequest request){
        request.setLimit(null);
        request.setPage(null);
        List<CustomerInfo> list = queryCustomerInfoListCommand.selectExcelData(request);
        if(CollectionUtil.isEmpty(list)){
            throw new WorkException(WorkCode.CUSTOMER_EXCEL_DATA_NULL);
        }
        ExcelData excelData = CustomerSal.makeExcelData(list);
        ExcelUtil.exportExcel(getHttpServletResponse(), "客户报表", excelData);
        return new EmptyResponse();
    }

    @RequestMapping(value = "download_template")
    public Object downloadTemplate(@RequestParam(value = "type") Integer type){
        if(type == null){
            throw new WorkException(WorkCode.INVALID_PARAM);
        }
        HttpServletResponse response = getHttpServletResponse();
        File file;
        String fileName;
        if(type.equals(UploadTypeEnum.IMPORT_ORDER.getType())){
            file = new File(ORDER_TEMPLATE_FILE_PATH);
            fileName = "导入-订单Excel模板";
        }else if(type.equals(UploadTypeEnum.IMPORT_CUSTOMER.getType())){
            file = new File(CUSTOMER_TEMPLATE_FILE_PATH);
            fileName = "导入-客户Excel模板";
        }else if(type.equals(UploadTypeEnum.PROJECT_COST.getType())){
            file = new File(PROJECT_COST_FILE_PATH);
            fileName = "导入-成本Excel模板";
        }
        else{
            throw new WorkException(WorkCode.INVALID_PARAM);
        }
        fileName = fileName + ExcelUtil.EXCEL_SUFFIX;
        if (file.exists()) {
            ServletOutputStream out = null;
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");

            // 告诉浏览器用什么软件可以打开此文件
            response.setHeader("content-Type", "multipart/form-data;charset=UTF-8");
            // 下载文件的默认名称
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            }catch (Exception e){
                e.printStackTrace();
            }
            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(file);
                out = response.getOutputStream();
                int b;
                byte[] buffer = new byte[1024];
                while ((b = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, b);
                }
            } catch (Exception e) {
                log.error("下载模板文件异常：", e);
                throw new WorkException(WorkCode.SYSTEM);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.flush();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else{
            throw new WorkException(WorkCode.TEMPLATE_FILE_NOT_EXIST);
        }

        return new EmptyResponse();
    }
}
